package com.starview.star.operators.string.runtime;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.starview.platform.data.EvaluationException;
import com.starview.platform.data.IPattern;
import com.starview.platform.data.IValue;
import com.starview.platform.data.type.IType;
import com.starview.platform.data.type.Refresher;
import com.starview.platform.data.type.StandardTypes;
import com.starview.platform.data.type.TypeUtils;
import com.starview.platform.data.value.Factory;
import com.starview.platform.data.value.NTuple;
import com.starview.star.operators.CafeEnter;

/**
 * The regexp builtin pattern is used to implement pattern matching against lists
 * 
 * @author fgm
 * 
 */

public class Regexp implements IPattern
{
  private final Pattern pattern;
  public static final String name = "__regexpMatch";

  public Regexp(String regexp)
  {
    if (regexp != null)
      this.pattern = Pattern.compile(regexp, java.util.regex.Pattern.DOTALL);
    else
      this.pattern = null;
  }

  @CafeEnter
  public String[] match(String tgt)
  {
    Matcher matcher = pattern.matcher(tgt);

    if (matcher.matches()) {
      String[] result = new String[matcher.groupCount()];

      for (int ix = 0; ix < matcher.groupCount(); ix++)
        result[ix] = matcher.group(ix + 1);

      return result;
    } else
      return null;
  }

  @Override
  public IValue match(IValue arg) throws EvaluationException
  {
    Matcher matcher = pattern.matcher(Factory.stringValue(arg));

    if (matcher.matches()) {
      IValue[] result = new IValue[matcher.groupCount()];

      for (int ix = 0; ix < matcher.groupCount(); ix++)
        result[ix] = Factory.newString(matcher.group(ix + 1));

      return NTuple.tuple(result);
    } else
      return null;
  }

  @Override
  public IType getType()
  {
    return Refresher.generalize(TypeUtils.patternType(TypeUtils.tupleType(), StandardTypes.stringType));
  }
}
